import 'package:flutter/material.dart';
import 'EmptyWidget.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart' as Refresh;

typedef BuildItemWidget<T> = Widget Function(BuildContext context, T t);
typedef BuildItem = Widget Function(BuildContext context, dynamic t);
typedef OnLoad = void Function(int page);
typedef LoadCallback = Future<void> Function();

class ListBaseWidget extends StatefulWidget {
  final BaseListView builder;

  const ListBaseWidget({Key key, @required this.builder})
      : assert(builder != null);

  @override
  State<StatefulWidget> createState() {
    return new ListBaseState();
  }
}

class ListBaseState extends State<ListBaseWidget>
    with SingleTickerProviderStateMixin {
  BaseListView builder;

  ///header
  static const HEADER_VIEW = 0x00000111;

  ///footer
  static const FOOTER_VIEW = 0x00000222;

  static const INVALID_TYPE = -1;
  EmptyWidget emptyWidget;
  int listTotalSize = 0;

  @override
  void initState() {
    super.initState();
    builder = widget.builder;
    builder.start();
  }

  /// 下拉刷新回调
  Future<Null> _pullToRefresh() async {
    builder.onRefresh();
    return null;
  }

  ///加载更多
  Future<Null> loadMore() async {
    builder.loadMore();
    return null;
  }

  ///公共的LoadView 默认是EmptyView
  @override
  Widget build(BuildContext context) {
    return new EmptyWidget(
      state: builder.emptyState,
      successWidget: child,
      errorRetry: () {
        builder.onRefresh();
      },
    );
  }

  Widget get child {
    Widget successView = new ListView.builder(
      itemCount: getItemCount(),
      itemBuilder: (context, i) => getItemWidget(context, i),
    );
    return Refresh.SmartRefresher(
      enablePullDown: builder.enableRefresh,
      enablePullUp: builder.enableLoadMore,
      header: builder.refreshIndicator,
      footer: builder.customFooter,
      controller: builder._refreshController,
      onRefresh: _pullToRefresh,
      onLoading: loadMore,
      child: successView,
    );
  }

  /// 获取Item的类型
  int getItemViewType(int position) {
    if (position < builder.headers.length) {
      return HEADER_VIEW;
    } else {
      int adjPosition = position - builder.headers.length;
      int itemCount = builder.listData.length;
      if (adjPosition < itemCount) {
        return INVALID_TYPE;
      } else {
        return FOOTER_VIEW;
      }
    }
  }

  ///返回绑定类型的Widget
  Widget getItemWidget(BuildContext context, int p) {
    int a = getItemCount();
    print("$a----$p");
    int viewType = getItemViewType(p);
    switch (viewType) {
      case HEADER_VIEW:
        print("getItemWidget----HEADER_VIEW");
        return builder.headerBuilder(context, builder.headers[p]);
      case FOOTER_VIEW:
        print('FOOTER_VIEW');
        int fixIndex = p - builder.headers.length - builder.listData.length;
        return builder.footerBuilder(context, builder.headers[fixIndex]);
      default:
        print("getItemWidget----ITEM_View");
        int fixIndex = p - builder.headers.length;
        return builder.itemBuilder(context, builder.listData[fixIndex]);
    }
  }

  ///总个数
  int getItemCount() {
    int count = builder.listData.length +
        builder.headers.length +
        builder.footers.length;
    return count;
  }
}

class BaseListView<T> {
  ///首次加载的状态
  LoadState emptyState = LoadState.State_Loading;
  Refresh.RefreshController _refreshController =
      Refresh.RefreshController(initialRefresh: false);

  ///加载更多的状态
  final Refresh.CustomFooter customFooter;

  ///下拉刷新
  Refresh.RefreshIndicator refreshIndicator;

  ///列表的 头部
  List<dynamic> headers = new List();

  ///列表的尾部
  List<dynamic> footers = new List();
  List<T> listData = new List<T>();
  bool headAndEmptyEnable;

  ///允许加载更多
  final bool enableLoadMore;

  ///允许下拉刷新
  final bool enableRefresh;

  ///分页是从几开始
  final int startPage;

  int curPage, tempPage = 0;

  ///item回调
  BuildItemWidget<T> itemBuilder;

  ///footerItem回调
  BuildItem footerBuilder;

  ///headerItem回调
  BuildItem headerBuilder;
  OnLoad onLoad;

  BaseListView(
      {this.startPage = 0,
      this.enableLoadMore = true,
      this.enableRefresh = true,
      this.headAndEmptyEnable,
      this.headerBuilder,
      this.footerBuilder,
      this.customFooter,
      this.refreshIndicator,
      @required this.itemBuilder,
      @required this.onLoad})
      : assert(itemBuilder != null),
        assert(onLoad != null) {
    refreshIndicator ??= new Refresh.WaterDropHeader();
  }

  ///开始
  void start() {
    print("start");
    onRefresh();
  }

  ///刷新
  void onRefresh() {
    tempPage = curPage = startPage;
    onLoad(curPage);
  }

  ///加载更多
  void loadMore() {
    tempPage = curPage;
    tempPage++;
    onLoad(tempPage);
  }

  void fail() => {
        /// 大于其实页说明是在加载下一页是造成的失败
        /// 允许加载更多
        if (tempPage > startPage && enableLoadMore)
          {_refreshController.loadFailed()}
        else
          {emptyState = LoadState.State_Success}
      };

  set headerData(data) => {headers.clear(), headers.add(data)};

  set addHeaderData(data) => headers.add(data);

  set footerData(data) => {footers.clear(), footers.add(data)};

  set addFooterData(data) => footers.add(data);

  set addData(List<T> data) => {
        print("loadComplete"),
        _refreshController.refreshCompleted(),
        _refreshController.loadComplete(),
        if (tempPage == startPage)
          {
            if (data.isEmpty)
              {
                ///如果和alder 有数据 列表为空时允许显示
                if (headAndEmptyEnable && headers.isNotEmpty)
                  {emptyState = LoadState.State_Success}
                else
                  {emptyState = LoadState.State_Empty},
              }
            else
              {emptyState = LoadState.State_Success, setNewData = data},
          }
        else
          {
            print("addDate"),
            curPage = tempPage,
            emptyState = LoadState.State_Success,
            listData.addAll(data),
            if (data.isEmpty) {_refreshController.loadNoData()}
          },
      };

  set setNewData(List<T> data) => {
        print("newDate"),
        if (listData.isNotEmpty) {listData.clear()},
        listData.addAll(data)
      };

  int getHeaderCount() => headers.length;

  int getFooterCount() => footers.length;
}

///可用于多布局的使用
///
/// 需 bean 类 extends MultiItemEntity
///
///
///
abstract class MultiItemEntity {
  int getItemType() => -1;
}

abstract class BaseMultiItemQuickAdapter<T extends MultiItemEntity>
    extends BaseListView<T> {}
